<?php
declare(strict_types=1);

/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/11
 * Time: 15:01
 */

namespace App\Model;


use Hyperf\Database\Model\Model;
use Hyperf\Database\Model\SoftDeletes;

class User extends Model
{
    use SoftDeletes;

    protected ?string $table='user';
    public bool $timestamps = true;

    protected array $hidden = [];

    protected array $fillable = [
        'auth_name','auth_key','user_type','party_id',
        'department','political_birthday','status','admin_id'
    ];


    public function party(): \Hyperf\Database\Model\Relations\BelongsTo
    {
        return $this->belongsTo(Party::class, 'party_id', 'id');
    }

    public function group(): \Hyperf\Database\Model\Relations\BelongsTo
    {
        return $this->belongsTo(Group::class, 'group_id', 'id');
    }

    public function setJobAttribute($value)
    {
        $this->attributes['job'] = implode(',', $value);
    }

    public function getJobAttribute($value): array
    {
        return $value != null ? explode(',', $value) : [];
    }


    /**
     * 根据openid获取用户信息
     * @param string $openid
     * @return object|null
     */
    static function getUserInfoByOpenId(string $openid): object|null
    {
        return User::where(['openid' => $openid])
            ->selectRaw('id,openid,nickname,avatar,sex,user_type,party_id')
            ->first();
    }


    /**
     * 根据uid获取用户信息(brief)
     * @param int $uid
     * @return object
     */
    static function getUserInfoByUserIdBrief(int $uid): object
    {
        return User::where(['id'=>$uid])
            ->selectRaw('id,nickname,avatar,sex,user_type,party_id')
            ->first();
    }

    /**
     * 根据uid获取用户信息
     * @param int $uid
     * @return object
     */
    static function getUserInfoByUserId(int $uid): object
    {
        return User::find($uid);
    }


    /**
     * 根据手机号获取用户信息
     * @param string $phone
     * @return object|null
     */
    static function getUserInfoByPhone(string $phone): object|null
    {
        return User::where('auth_phone',$phone)
            ->selectRaw('id,nickname,avatar,sex,user_type,party_id')
            ->first();
    }

}